﻿@model IMS_FinanceRecv
@{
	ViewBag.Title = (Model.ID > 0 ? "修改" : "新增") + "收款单";
}
@section header{
	@*<link href="~/lib/select2/select2.min.css" rel="stylesheet" asp-append-version="true" />*@
	<style>
		.detail-content-info, .detail-content-label {
			padding: 3px;
		}
	</style>
}
@section quickmenu{
	<td style="padding-right: 0px; padding-left: 10px;">
		<span style="cursor: pointer;" title="返回..." @@click="pageBack">
			<i class="icon-reply icon-2x pull-left icon-border crm-bu-style"></i>
		</span>
	</td>
}

<table style="border:0;margin:0;border-spacing:0;width:100%;padding:0 15px 10px 15px;overflow:auto;table-layout:fixed;">
	<tbody>
		<tr>
			<td class="detail-left-td">
				<div class="detail-panel-div">
					<div class="detail-inner">
						<div class="detail-name-div" title="@(Model.ID>0?Model.SNo:"新增收款单")">
							@(Model.ID > 0 ? Model.SNo : "新增收款单")
						</div>
					</div>
					<div class="detail-heading">
						相关记录
					</div>
					<div class="detail-inner detail-related">
						<div class="detail-list-div-disabled" v-for="(ritem) in related">
							{{ritem.name}}
						</div>
					</div>
					<div class="detail-exit">&nbsp;</div>
				</div>
			</td>
			<td style="vertical-align:top;" class="detail-content-td">
				<div style="width:100%;margin:0;padding:0;" v-show="viewid=='main'">
					<table style="width:100%;">
						<tr>
							<td style="vertical-align:top;">
								<form id="frmEdit">
									<div class="detail-panel-div" style="position:relative;overflow:auto;">
										<table border="0" cellspacing="0" cellpadding="5" style="height:42px;width:100%;table-layout:fixed;">
											<tbody>
												<tr class="detail-content-heading" style="height: 28px;">
													<td>
														<b>&nbsp;基本信息&nbsp;</b>
													</td>
												</tr>
												<tr>
													<td>
														<table border="0" cellspacing="0" cellpadding="0" style="width:100%;">
															<tr style="height: 25px">
																<td class="detail-content-label">
																	收款单编号
																</td>
																<td class="detail-content-info">
																	<input type="text" class="detailedViewTextBox input-sm" readonly v-model="model.SNo" placeholder="自动生成">
																</td>
																<td class="detail-content-info" colspan="2"></td>
															</tr>
															<tr style="height: 25px">
																<td class="detail-content-label label-required" width="20%">
																	客户/供应商
																</td>
																<td class="detail-content-info" width="30%">
																	<input type="text" id="txtKeyword" v-model="model.PartnerName" class="detailedViewTextBox validate[required]" @@keypress.prevent.enter="handleKeypressKeyword" autocomplete="off" style="ime-mode:disabled;" placeholder="输入拼音助记码/名称查找" />
															@* 		<input type="text" class="detailedViewTextBox input-sm" v-model="model.PartnerName" readonly style="cursor:pointer;" onclick="openPopPartner();">
																	<button class="pure-button pure-button-edit pure-icon-bu" style="width: 23px; height: 21px;margin-right:5px;" title="选择" onclick="openPopPartner();return false;">
																		<i class="icon-search"></i>
																	</button>
																	<button class="pure-button pure-button-approve pure-icon-bu" style="width: 23px; height: 21px;" title="清除" onclick="clearPopPartner();return false;">
																		<i class="icon-remove"></i>
																	</button> *@
																</td>
																<td class="detail-content-label" width="20%"></td>
																<td class="detail-content-info" width="30%"></td>
															</tr>
															<tr>
																<td class="detail-content-label label-required">
																	收款日期
																</td>
																<td class="detail-content-info">
																	<input type="text" class="detailedViewTextBox input-sm calendar validate[required]" id="RecvDate" style="" maxlength="19" readonly />
																	<i class="icon-calendar calendar-tgr" id="RecvDateTgr"></i>
																</td>
																<td class="detail-content-label">
																	是否开发票
																</td>
																<td class="detail-content-info">
																	<input type="checkbox" v-model="model.Invoice" />开发票
																</td>
															</tr>
															<tr>
																<td class="detail-content-label">
																	备注
																</td>
																<td class="detail-content-info" colspan="3">
																	<textarea v-model="model.Comment" style="height:35px;"></textarea>
																</td>
															</tr>
														</table>
													</td>
												</tr>
												<tr class="detail-content-heading" style="height: 28px;">
													<td>
														<b>&nbsp;收款明细&nbsp;</b>
													</td>
												</tr>
												<tr>
													<td>
														<table class="edit-table padding3" id="tblDetail" border="0" cellpadding="3" cellspacing="1" style="table-layout:fixed;width:100%;">
															<tr class="windLayerHead" height="25px">
																<td style="text-align:center;">
																	<b>序号</b>
																</td>
																<td style="text-align:center;">
																	<b>应收款单</b>
																</td>
																<td style="text-align:center;">
																	<b>相关业务类型</b>
																</td>
																<td style="text-align:center;"><b>相关业务单号</b></td>
																<td style="text-align:center;"><b>期次</b></td>
																<td style="text-align:center;"><b>应收日期</b></td>
																<td style="text-align: right;">
																	<b>应收金额</b>
																</td>
																<td style="text-align: right;">
																	<b>已收金额</b>
																</td>
																<td style="text-align: right;">
																	<b>剩余金额</b>
																</td>
																<td style="text-align: right;">
																	<b>本次收款</b>
																</td>
																<td style="text-align: center;">
																	<input type="checkbox" name="selectall" @@click="detailToggle($event)" v-model="selectAll" />
																</td>
															</tr>
															<tr v-for="(ditem,didx) in model.Details">
																<td style="text-align: center;">{{didx+1}}</td>
																<td style="text-align:center;">
																	{{ditem.DueRecv.SNo}}
																</td>
																<td style="text-align:center;">
																	{{ditem.DueRecv.BuzType | formatBuzType}}
																</td>
																<td style="text-align:center;">
																	{{ditem.DueRecv.BuzSNo}}
																</td>
																<td style="text-align:center;">
																	{{ditem.DueRecv.Stage}}
																</td>
																<td style="text-align:center;">
																	{{ditem.DueRecv.DueDate | formatDate("yyyy-MM-dd")}}
																</td>
																<td style="text-align: right;">
																	{{ditem.DueRecv.TotalRecvDue}}
																</td>
																<td style="text-align: right;">
																	{{ditem.DueRecv.TotalRecved}}
																</td>
																<td style="text-align: right;">
																	{{ditem.DueRecv.TotalRecvLeft}}
																</td>
																<td style="text-align: center;">
																	<input type="number" name="Recved" style="text-align: right;font-weight:bold;" class="detailedViewTextBox amount" :class="ditem.RecvedValidate" v-model="ditem.Recved" @@keypress.prevent.enter="handleKeypressDetailLast" :style="ditem.RecvedStyles" :readonly="!ditem.RecvedEditable" @@change="handleChangeRecved" />
																</td>
																<td style="text-align: center;">
																	<input type="checkbox" name="DueID" :value="ditem.DueRecv.ID" v-model="selected" :data-idx="didx" @@change="detailCheck($event)" />
																</td>
															</tr>
															<tr>
																<td colspan="9" style="text-align:right;">选中合计金额：</td>
																<td style="font-weight:bold;text-align:right;">
																	￥{{totalSelectedRecv}}
																</td>
																<td></td>
															</tr>
															<tr>
																<td colspan="9" style="text-align:right;">本次收款合计：</td>
																<td style="font-weight:bold;text-align:right;">
																	<input type="number" name="TotalRecv" style="text-align: right;font-weight:bold;" class="detailedViewTextBox validate[required,custom[positive]]" v-model="model.TotalRecv" />
																</td>
																<td></td>
															</tr>
															<tr>
																<td colspan="9" style="text-align:right;">收款方式：</td>
																<td colspan="2">
																	<template v-for="(st,stidx) in shareType">
																		<input type="checkbox" name="ShareType" :value="st.value" @@click="changeShareType($event)" :checked="model.ShareType==st.value" />
																		{{st.text}}
																		<br />
																	</template>
																</td>
															</tr>
														</table>
													</td>
												</tr>
												<tr style="height: 38px;">
													<td style="text-align:center;">
														<button type="submit" class="pure-button pure-button-edit" onclick="$('#frmEdit').submit();return false;" style="margin-right:50px;">
															<i class="icon-check"></i>&nbsp;保存&nbsp;
														</button>
														<button class="pure-button" @@click.prevent='pageBack'>
															<i class="icon-undo"></i>&nbsp;取消&nbsp;
														</button>
													</td>
												</tr>
											</tbody>
										</table>
									</div>
								</form>
							</td>
						</tr>
					</table>
				</div>
			</td>
		</tr>
	</tbody>
</table>
@section footer{
	<script src="~/js/related/sys_attachment.js" asp-append-version="true"></script>
	<script src="~/js/pinyin.js" asp-append-version="true"></script>
	<script src="~/lib/jquery.autocomplete-1.4.10.js" asp-append-version="true"></script>
	<script src="~/lib/math-6.1.0.min.js" asp-append-version="true"></script>
	@*日期必须开始*@
	<script src="~/lib/laydate/laydate.js" asp-append-version="true"></script>
	@*日期必须结束*@
	<script src="~/lib/validationEngine/jquery.validationEngine.min.js" asp-append-version="true"></script>
	<script src="~/lib/validationEngine/jquery.validationEngine-zh_CN.js" asp-append-version="true"></script>
	<link href="~/lib/validationEngine/validationEngine.jquery.css" rel="stylesheet" asp-append-version="true" />
	@*验证结束*@
	@*列表相关开始*@
	<script type="text/javascript">
		var pageEnumData = {
			buztype:@(Json.Serialize(ViewBag.BuzTypeOptions)),
			sharetype:@(Json.Serialize(ViewBag.ShareTypeOptions)),
		};
		var modelJson=@(Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model,new Newtonsoft.Json.JsonSerializerSettings()
				   {
				   DateFormatString = "yyyy-MM-dd HH:mm:ss"
					})));
		var modelData = $.extend(modelJson, {
		});
		var pageData = {
			hideBreadcrumb: false,
			serviceCode: '@(ViewBag.ServiceCode)',
			global: globalData,
			viewid: 'main',
			related: @(Json.Serialize(ViewBag.RelatedModules)),
			model: modelData,
			selected: [],
			shareType: pageEnumData.sharetype,
			selectAll: false,
			totalSelectedRecv:0
		};
		var selectedDetail = modelData.Details || [];
		var pageApp = new Vue({
			el: '#app',
			data: pageData,
			created: function () {
				if (!!modelData.PartnerID) {
					refreshDueList(modelData.PartnerID);
				}
				var details = modelData.Details || [];
				this.selected = details.map(function (val) {
					return val.DueRecv ? val.DueRecv.ID : 0;
				});
				this.dealDetail(details);
			},
			mounted: function () {
			},
			methods: {
				pageBack: function() {
					//history.go(-1);
					if (@(Model.ID>0?"true":"false")) {
						history.back();
					} else {
						location.href = '@(Url.Action("List", "FinanceRecv"))?nc=' + new Date().getTime();
					}
				},
				pageSave: function (details) {
					var newModelData = Object.assign({}, modelData, {
						Details:details
					});
					utils.ajaxPost('@(Url.Action("Save", "FinanceRecv"))', newModelData, function (resp) {
						utils.success("保存成功");
						location.href = '@(Url.Action("ViewDetail", "FinanceRecv",new {id="" }))/'+resp.data+'?nc=' + new Date().getTime();
					}, function (msg) {
						utils.alert(msg);
					});
				},
				handleSave: function () {
					var detailsAll = this.model.Details || [];
					var selected = this.selected || [];
					var details = detailsAll.filter(function (item) {
						return selected.findIndex(function (val) { return val == item.DueRecv.ID; }) >= 0;
					});
					var self = this;
					if (details.length == 0) {
						utils.confirm('没有选中应收款，确认直接收款？', function () {
							self.pageSave(details);
						});
					} else {
						self.pageSave(details);
					}
				},
				relatedChange: function (vid, e) {
					switch (e.action) {
						case "total":
							{
								this.related = this.related.map(function (item) {
									if (item.id == vid) {
										return Object.assign({}, item, { count: e.data });
									} else {
										return item;
									}
								});
							}
							break;
					}
				},
				changeView: function(vid) {
					this.viewid = vid;
					this.$refs[vid]&&this.$refs[vid].reload();
				},
				resetView: function() {
					this.viewid = 'main';
				},
				detailToggle: function (e) {
					var checked = (e.srcElement || e.target).checked;
					if (checked) {
						this.selected = (this.model.Details || []).map(function (item) {
							return item.DueRecv.ID;
						});
					} else {
						this.selected = [];
					}
					this.dealDetail(this.model.Details || []);
					this.calcTotalRecv();
				},
				detailCheck: function (e) {
					var obj = e.srcElement || e.target;
					var idx = parseInt(obj.dataset.idx, 10);
					var newObj = this.dealDetailItem(this.model.Details[idx]);
					this.model.Details.splice(idx, 1, newObj);
					this.calcTotalRecv();
				},
				changeShareType: function (e) {
					var obj = e.srcElement || e.target;
					this.model.ShareType = obj.value;
					obj.checked = true;
					this.dealDetail(this.model.Details || []);
					this.calcTotalRecv();
				},
				handleChangeRecved: function (e) {
					this.calcTotalRecv();
				},
				calcTotalRecv: function () {
					var selected = this.selected || [];
					var totalSelected= this.model.Details.reduce(function (total, item) {
						if (selected.findIndex(function (val) { return val == item.DueRecv.ID; }) < 0) {
							return math.bignumber(total);
						} else {
							return math.bignumber(total).add(math.bignumber(item.Recved));
						}
					 }, 0);
					this.totalSelectedRecv = math.format(totalSelected, { notation: 'fixed', precision: 2 });
				},
				dealDetail: function (details) {
					var _this = this;
					this.model.Details = details.map(function (item) {
						return _this.dealDetailItem(item);
					});
				},
				dealDetailItem: function (item) {
					var selected = this.selected || [];
					var _this = this;
					var editable = selected.findIndex(function (val) { return val == item.DueRecv.ID; }) >= 0 && _this.model.ShareType == @((int)FinanceShareType.不自动分配);
					return Object.assign({}, item, {
						Recved: editable ? item.Recved : math.format(math.bignumber(item.DueRecv.TotalRecvDue).sub(math.bignumber(item.DueRecv.TotalRecved)), { notation: 'fixed', precision: 2 }),
						RecvedEditable: editable,
						RecvedStyles: {
							backgroundColor: editable ? "#ffffff" : "#e6e6e6"
						},
						RecvedValidate:_defineProperty({}, 'validate[required,custom[positive], max[' + item.DueRecv.TotalRecvLeft + ']]', editable)
					});
				}
			},
			computed: {
				currentM: function () {
					var currentM = null;
					var i;
					var j;
					for (i = 0; i < this.global.modules.length; i++) {
						for (j = 0; j < this.global.modules[i].Services.length; j++) {
							if (this.serviceCode == this.global.modules[i].Services[j].Code) {
								currentM = this.global.modules[i];
								break;
							}
						}
					}
					return currentM;
				},
				currentS: function () {
					var currentS = null;
					var i;
					var j;
					for (i = 0; i < this.global.modules.length; i++) {
						for (j = 0; j < this.global.modules[i].Services.length; j++) {
							if (this.serviceCode == this.global.modules[i].Services[j].Code) {
								currentS = this.global.modules[i].Services[j];
								break;
							}
						}
					}
					return currentS;
				}
			},
			filters: {
				formatBuzType: function (val) {
					return utils.formatEnum(val, pageEnumData.buztype);
				}
			}
		});

		$(document).ready(function () {
			$("#frmEdit").keypress(function (e) {
				if (e.keyCode == 13) {
					return false;
				}
			}).validationEngine({
				scroll: false,
				validateNonVisibleFields: false,
				autoHidePrompt: true,
				showOneMessage: true,
				ajaxFormValidationMethod: 'post',
				custom_error_messages: {
					'.amount': {
						'max': {
							'message': '金额不能大于剩余金额'
						}
					}
				},
				onValidationComplete: function (form, status) {
					if (!status) {
						return;
					}
					if (!pageApp.model.PartnerID || !pageApp.model.PartnerName) {
						utils.alert("请选择客户或供应商");
						return;
					}
					pageApp.handleSave();
				}
			});

			var uinfoJson = localStorage.getItem('uinfo');
			var uinfo = uinfoJson ? JSON.parse(uinfoJson) : {};

			$('#txtKeyword').autocomplete({
				serviceUrl: '@(Url.Action("Autocomplete", "Partner"))',
				params: { limit: '' },
				ajaxSettings: {
					headers: {
						skey: uinfo.skey || "",
						ucode: uinfo.ucode || ""
					}
				},
				//groupBy: 'catname',
				// width:600,
				formatResult: function (suggestion, value, i) {
					return '<a>\
						<span style="color:#000;">'+ (suggestion.Name || "") + '</span>\
					</a>';
				},
				onSearchStart: function (params) {
				},
				onSelect: function (suggestion) {
					this.value = suggestion.Name;
					modelData.PartnerID = suggestion.ID;
					modelData.PartnerName = suggestion.Name;
					refreshDueList(suggestion.ID);
				}
			});

			$('#RecvDateTgr').click(function () {
				laydate.render({
					elem: '#RecvDate'
					, show: true //直接显示
					, value: modelData.RecvDate && modelData.RecvDate.substr(0, 10) || ''
					, closeStop: '#RecvDateTgr'
					, done: function (value, date) {
						modelData.RecvDate = value;
					}
				});
			});

			laydate.render({
				elem: '#RecvDate'
				, value: modelData.RecvDate && modelData.RecvDate.substr(0, 10) || ''
				, closeStop: '#RecvDateTgr'
				, done: function (value, date) {
					modelData.RecvDate = value;
				}
			});
		});

		// function openPopPartner() {
		// 	utils.layerFull('@(Url.Action("PopList", "Partner"))?type=@((int)PartnerType.布行)&callback=popPartnerCallback', "选择客户", "Partner");
		// }

		// function popPartnerCallback(index, ret) {
		// 	if (!ret) {
		// 		return;
		// 	}
		// 	modelData.PartnerID = ret.ID;
		// 	modelData.PartnerName = ret.Name;//
		// 	refreshDueList(ret.ID);
		// }

		// function clearPopPartner() {
		// 	modelData.PartnerID = 0;
		// 	modelData.PartnerName = "";
		// 	modelData.Details = [];
		// }

		function refreshDueList(fromID) {
			var dueIDs = selectedDetail.map(function (val) {
				return val.DueRecv ? val.DueRecv.ID:0;
			});
			utils.ajaxPost('@(Url.Action("SearchByFrom", "FinanceRecvDue"))', { partnerid: fromID, dueids: dueIDs.join(',')}, function (resp) {
				var details = (resp.data || []).map(function (val) {
					pageApp.selected.push(val.ID);
					var selectedIndex = selectedDetail.findIndex(function (detail) {
						return detail.DueRecv.ID == val.ID;
					});
					if (selectedIndex < 0) {
						return {
							DueID: val.ID,
							DueSNo: val.SNo,
							DueRecv: val,
							Recved: val.TotalRecvLeft
						};
					} else {
						return selectedDetail[selectedIndex];
					}
				});
				pageApp.selectAll = true;
				pageApp.dealDetail(details);
				pageApp.calcTotalRecv();
			}, function (msg) {
			});
		}
	</script>
	@*列表相关结束*@
}